// Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
	"fmt"
	"os"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

const AppName = "cmd"

var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "cobra",
	Short: "A brief description of your application",
	Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	Run: func(cmd *cobra.Command, args []string) {
		// print flags value
		if value, err := cmd.Flags().GetBool("print"); value && err == nil {
			fmt.Println("config", viper.Get("config"))
			fmt.Println("value", viper.Get("value"))
			fmt.Println("bind:", viper.Get("bind"))
		}
	},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute(use string) {
	rootCmd.Use = use

	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func SetShortDesc(desc string) {
	rootCmd.Short = desc
}

func SetLongDesc(desc string) {
	rootCmd.Long = desc
}

// AddCommand adds one or more commands to this parent command.
func AddCommand(cmds ...*cobra.Command) {
	rootCmd.AddCommand(cmds...)
}

func init() {
	cobra.OnInitialize(initConfig)

	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.
	usage := fmt.Sprintf("config file (default is config.yaml from . $HOME/.%s /etc/%s)", AppName, AppName)
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", usage)
	rootCmd.PersistentFlags().StringP("bind", "b", ":50051", "address for grpc")
	rootCmd.PersistentFlags().BoolP("print", "p", false, "print flags value")
	//rootCmd.PersistentFlags().String("addr", ":50051", "address for grpc")

	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	//rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
	rootCmd.Flags().StringP("value", "v", "", "Help message for toggle")
	rootCmd.Flags().Bool("graceful", false, "Graceful restart")

	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
		fmt.Println("config", viper.Get("config"))
		fmt.Println("value", viper.Get("value"))
		fmt.Println("bind:", viper.Get("bind"))
	})

}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		viper.SetConfigName("config")                // name of config file (without extension)
		viper.AddConfigPath(".")                     // optionally look for config in the working directory
		viper.AddConfigPath("$HOME/." + rootCmd.Use) // call multiple times to add many search paths
		viper.AddConfigPath("/etc/" + rootCmd.Use)   // path to look for the config file in
	}
	// set the environment variables prefix
	viper.SetEnvPrefix(rootCmd.Use)
	// read in environment variables that match
	viper.AutomaticEnv()
	// bind flag to viper
	viper.BindPFlags(rootCmd.Flags())

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		cfgFile = viper.ConfigFileUsed()
		fmt.Println("Using config file:", cfgFile)
		viper.WatchConfig()
	} else {
		//fmt.Println("Parse config file:", cfgFile, "error:", err)
	}
}
